package com.it.demo.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.it.demo.annotation.RepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@Aspect
public class NoRepeatSubmitAspect {

    @Resource
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(repeatSubmit)")
    public void pointCutNoRepeatSubmitAspect(RepeatSubmit repeatSubmit) {

    }

    @Around("pointCutNoRepeatSubmitAspect(repeatSubmit)")
    public Object around(ProceedingJoinPoint joinPoint,RepeatSubmit repeatSubmit) throws Throwable {
        String reqSignature = buildReqSignature(joinPoint);
        //加锁时间
        long lockTime = repeatSubmit.lockTime();
        Boolean res = redisTemplate.opsForValue().setIfAbsent(reqSignature, 1, lockTime, TimeUnit.SECONDS);
        if(!res){
            throw new RuntimeException("重复请求！");
        }
        return joinPoint.proceed();
    }

    /**
     * 构建请求签名
     * @param joinPoint
     * @return
     */
    private String buildReqSignature(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(Objects.isNull(requestAttributes)){
            throw new RuntimeException("请求参数异常！");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String remoteAddr =request.getRemoteAddr()  + ":" +  request.getRemoteHost();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        StringBuffer sb = new StringBuffer();
        for (Object arg : joinPoint.getArgs()) {
            sb.append(arg);
        }
        //请求签名(MD5加密)
        return DigestUtil.md5Hex(StrUtil.format("{}-{}-{}-{}",remoteAddr,method,requestURI,sb));
    }
}
